package com.hrt.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

public class ReadFromFile {
	/**
	 * 以字节为单位读取文件，常用于读二进制文件，如图片、声音、影像等文件。
	 */
	static File uploadPath=null;
	public static String readFileByBytes(String fileName,HttpServletRequest request) {
		//准备上传的图片
		File fileUpload = new File(fileName);
		FileInputStream fin = null;
		FileOutputStream ous = null;
		//存储的图片
		Long time = System.currentTimeMillis();
		String name = String.valueOf(time)+".png";
		File toFile = createFile(request,name);
		try {
			fin = new FileInputStream(fileUpload);
			ous = new FileOutputStream(toFile);
			int tempbyte;
			while ((tempbyte = fin.read()) != -1) {
				ous.write(tempbyte);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭输入流
				fin.close();
				//关闭输出流
				ous.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String rename = uploadPath.getAbsolutePath()+"\\"+name;
		return rename;
	}
	
	/**
	 * @param request
	 * @return
	 * 创建文件
	 */
	public static File createFile(HttpServletRequest request,String photoName) {
		File file= null;
		try {
			String uploadPathStr =WebParams.WEB_UPLOAD_FOLDER;
	
			uploadPath = new File(uploadPathStr);
			if (!uploadPath.exists()) {
				uploadPath.mkdirs();
			}
			System.out.println(uploadPath.getAbsolutePath());
			
			file = new File(uploadPath + "/"+photoName);
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;

	}
	
	
	public static void readFile(InputStream ins)
	{
		File file=new File("d:\test.png");
		InputStreamReader  fins=new InputStreamReader(ins);
		int b=0;
		FileOutputStream baos;
		try {
			baos = new FileOutputStream(file);
			while((b=fins.read())!=-1)
			{
				baos.write(b);
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}